package hz.mobileproject.pda.ui.activity.work;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.db.DBManager;
import hz.mobileproject.pda.entity.request.Request_Edu_inter;
import hz.mobileproject.pda.entity.response.Rp_ContentSummary;
import hz.mobileproject.pda.entity.response.Rp_eduType;
import hz.mobileproject.pda.entity.response.Rp_eduTypeArrList;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.ui.adapter.ContentSummaryAdapter;
import hz.mobileproject.pda.ui.adapter.EduUploadPopAdapter;
import hz.mobileproject.pda.ui.adapter.PopListViewAdapter;
import hz.mobileproject.pda.ui.base.BaseActivity;
import hz.mobileproject.pda.ui.view.CustomPopWindow;
import hz.mobileproject.pda.ui.view.EduTalkTrackDialog;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.HttpRqUtils;

@ContentView(R.layout.activity_edu_talk_evaluate)
public class EduTalkEvaluateActivity extends BaseActivity implements ExpandableListView.OnGroupClickListener {
    @ViewInject(R.id.elv_content_summary)
    private ExpandableListView elv_content_summary;
    @ViewInject(R.id.tv_weixian_pinggu)
    private TextView tv_weixian_pinggu;
    @ViewInject(R.id.tv_weixian_pinggu2)
    private TextView tv_weixian_pinggu2;
    @ViewInject(R.id.tv_talk_pinggu)
    private TextView tv_talk_pinggu;
    @ViewInject(R.id.tv_qingxu_pinggu)
    private TextView tv_qingxu_pinggu;
    @ViewInject(R.id.et_location)
    private EditText et_location;
    @ViewInject(R.id.tv_is_attention)
    private TextView tv_is_attention;
    @ViewInject(R.id.et_chief)
    private EditText et_chief;
    @ViewInject(R.id.et_talk_observal)
    private EditText et_talk_observal;
    @ViewInject(R.id.et_talk_process)
    private EditText et_talk_process;
    @ViewInject(R.id.et_option_feedback)
    private EditText et_option_feedback;
    @ViewInject(R.id.et_exist_problem)
    private EditText et_exist_problem;

    private Gson mGson;
    public DBManager dBManager;
    private LoadingDialog mLoadingDialog;
    private ContentSummaryAdapter mAdapter;
    //谈话配置
    private Rp_eduTypeArrList mEduTypeArrList;
    //当前选中 - 危险评估
    private Rp_eduType mSelectedDangerEvaluate;
    //当前选中 - 危险评估子项
    private Rp_eduType mSelectedDangerEvaluateSon;
    //当前选中 - 谈话评估
    private Rp_eduType mSelectedTalkEffect;
    //当前选中 - 情绪评估
    private Rp_eduType mSelectedEmotionEvaluate;
    //提交请求实体类
    private Request_Edu_inter mInter;


    private List<String> strAttionStr = new ArrayList<>();

    @Override
    protected void initData() {
        mGson = new Gson();
        dBManager = DBManager.getInstance(getApplicationContext());
        mLoadingDialog = new LoadingDialog(this);
        elv_content_summary.setOnGroupClickListener(this);
        elv_content_summary.setOnChildClickListener(null);
        mInter = (Request_Edu_inter) getIntent().getSerializableExtra(Constance.EDU_UPLUAD_TO_EVALUATE_INTER);
        mEduTypeArrList = (Rp_eduTypeArrList) getIntent().getSerializableExtra(Constance.EDU_UPLUAD_TO_EVALUATE_EDUTYPE);
        mAdapter = new ContentSummaryAdapter(this, new ArrayList<Rp_ContentSummary>());
        elv_content_summary.setAdapter(mAdapter);
        //TODO 从服务器获取内容概要数据
        getContentSummary();
        strAttionStr.add("是");
        strAttionStr.add("否");


    }


    /**
     * 去除ExpandableListView父节点点击事件
     */
    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
        return true;
    }

    @Event({R.id.tv_weixian_pinggu, R.id.tv_weixian_pinggu2, R.id.tv_talk_pinggu, R.id.tv_qingxu_pinggu,
            R.id.btn_submit,R.id.tv_is_attention})
    private void viewOnClick(View v) {
        switch (v.getId()) {
            case R.id.tv_weixian_pinggu://点击危险评估
                showPopWindow(mEduTypeArrList.getDanger_evaluate(), tv_weixian_pinggu);
                break;
            case R.id.tv_weixian_pinggu2://点击危险评估子项
                if (mSelectedDangerEvaluate == null) {
                    ToastUtils.showLong("请先选择危险评估");
                    return;
                }
                showPopWindow(mSelectedDangerEvaluate.getSub_data(), tv_weixian_pinggu2);
                break;
            case R.id.tv_talk_pinggu://点击谈话评估
                showPopWindow(mEduTypeArrList.getTalk_effect(), tv_talk_pinggu);
                break;
            case R.id.tv_qingxu_pinggu://点击情绪评估
                showPopWindow(mEduTypeArrList.getEmotion_evaluate(), tv_qingxu_pinggu);
                break;
            case R.id.btn_submit://提交
                afterSubmit();
                break;
            case R.id.tv_is_attention:
                showPopWindow2(strAttionStr,tv_is_attention);
                break;
        }
    }


    private void showPopWindow2(final List<String> stringList, final View showAsDropDownView) {
        if (stringList == null || stringList.size() <= 0) {
            return;
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_custom_list, null);
        //处理popWindow 显示内容
        ListView listView = (ListView) contentView.findViewById(R.id.lv_dialog);
        PopListViewAdapter adapter = new PopListViewAdapter(this, stringList);
        adapter.setColor("#eeeeee", "#4084E4");
        listView.setAdapter(adapter);
        //创建并显示popWindow
        final CustomPopWindow mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(showAsDropDownView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAsDropDown(showAsDropDownView, 0, 10);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mListPopWindow.dissmiss();
                ((TextView) showAsDropDownView).setText(stringList.get(position));
            }
        });
    }


    /**
     * 弹出选择项popwindow
     *
     * @param eduTypes
     * @param showAsDropDownView
     */
    private void showPopWindow(final List<Rp_eduType> eduTypes, final View showAsDropDownView) {
        if (eduTypes == null || eduTypes.size() <= 0) {
            return;
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_custom_list, null);
        //处理popWindow 显示内容
        ListView listView = (ListView) contentView.findViewById(R.id.lv_dialog);
        EduUploadPopAdapter adapter = new EduUploadPopAdapter(this, eduTypes);
        listView.setAdapter(adapter);
        //创建并显示popWindow
        final CustomPopWindow mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(showAsDropDownView.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .create()
                .showAsDropDown(showAsDropDownView, 0, 0);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mListPopWindow.dissmiss();
                ((TextView) showAsDropDownView).setText(eduTypes.get(position).getDisplay_field());
                switch (showAsDropDownView.getId()) {
                    case R.id.tv_weixian_pinggu://点击危险评估
                        mSelectedDangerEvaluate = eduTypes.get(position);
                        mSelectedDangerEvaluateSon = null;
                        tv_weixian_pinggu2.setText("");
                        break;
                    case R.id.tv_weixian_pinggu2://点击危险评估子项
                        mSelectedDangerEvaluateSon = eduTypes.get(position);
                        break;
                    case R.id.tv_talk_pinggu://点击谈话评估
                        mSelectedTalkEffect = eduTypes.get(position);
                        break;
                    case R.id.tv_qingxu_pinggu://点击情绪评估
                        mSelectedEmotionEvaluate = eduTypes.get(position);
                        break;
                }
            }
        });
    }


    /**
     * 提交谈话前条件判断
     */
    private void afterSubmit() {
        if (mSelectedDangerEvaluate == null) {
            ToastUtils.showLong("请选择危险类别");
            return;
        }
        if (mSelectedDangerEvaluateSon == null) {
            ToastUtils.showLong("请选择危险详情");
            return;
        }
        if(!mSelectedDangerEvaluate.getDisplay_value().equals(mSelectedDangerEvaluateSon.getDisplay_value().substring(0,1))){
            ToastUtils.showLong("危险类别与危险详情不匹配");
            return;
        }
        if (mSelectedTalkEffect == null) {
            ToastUtils.showLong("请选择谈话评估");
            return;
        }
        if (mSelectedEmotionEvaluate == null) {
            ToastUtils.showLong("请选择情绪评估");
            return;
        }
        if (mAdapter.getCheckedList().size() < Constance.CONTENT_SUMMARY_MIN_SELECTED) {
            ToastUtils.showLong("至少选择"+Constance.CONTENT_SUMMARY_MIN_SELECTED+"项内容概要");
            return;
        }

        String location = checkIsInput(et_location,"请输入地点");
        String is_attention = checkIsInput(tv_is_attention,"请输入是否重点关注");
        String chief = checkIsInput(et_chief,"请输入主诉");
        String talk_observal = checkIsInput(et_talk_observal,"请输入谈话警察观察");
        String talk_process = checkIsInput(et_talk_process,"请输入谈话过程,谈话方法");
        String option_feedback = checkIsInput(et_option_feedback,"请输入意见及反馈");
        String exist_problem = checkIsInput(et_exist_problem,"请输入存在问题及自我反思");
        if(StringUtils.isEmpty(location) || StringUtils.isEmpty(is_attention) || StringUtils.isEmpty(chief)
                || StringUtils.isEmpty(talk_observal) || StringUtils.isEmpty(talk_process) || StringUtils.isEmpty(option_feedback)
                || StringUtils.isEmpty(exist_problem)
        ) {
            return;
        }
        mInter.setLocation(location);
        if("是".equals(is_attention)) {
            mInter.setIs_attention("1");
        }else if("否".equals(is_attention)) {
            mInter.setIs_attention("2");
        }
        mInter.setChief(chief);
        mInter.setTalk_observal(talk_observal);
        mInter.setTalk_process(talk_process);
        mInter.setOption_feedback(option_feedback);
        mInter.setExist_problem(exist_problem);

        if ((!Constance.DANGER_EVALUATE_OK.equals(mSelectedDangerEvaluate.getDisplay_value())) ||
                (!Constance.EMOTION_EVALUATE_OK.equals(mSelectedEmotionEvaluate.getDisplay_value())) ||
                (!Constance.TALK_EFFECT_OK.equals(mSelectedTalkEffect.getDisplay_value()))) {
            EduTalkTrackDialog dialog = new EduTalkTrackDialog(this, mEduTypeArrList.getStep_id());
            dialog.setOnClickListener(new EduTalkTrackDialog.OnClickListener() {
                @Override
                public void onPositive(List<Rp_eduType> listData) {
                    StringBuilder strs = new StringBuilder();
                    if (listData != null) {
                        for (Rp_eduType tempdata : listData) {
                            if (StringUtils.isEmpty(strs)) {
                                strs.append(tempdata.getDisplay_value());
                            } else {
                                strs.append("," + tempdata.getDisplay_value());
                            }
                        }
                    }
                    submitInterToSer(strs.toString());
                }
            }).show();
        } else {
            submitInterToSer("");
        }
    }


    public String checkIsInput(View et,String toastStr) {
        String str = null;
        if(et instanceof EditText) {
            str = ((EditText)et).getText().toString().trim();
        }else if(et instanceof TextView) {
            str = ((TextView)et).getText().toString().trim();
        }
        if(StringUtils.isEmpty(str)) {
            ToastUtils.showShort(toastStr);
            return "";
        }else {
            return str;
        }
    }



    /**
     * 调用接口获取内容概要
     */
    private void getContentSummary() {
        HttpRqUtils.httpGet(Constance.BASE_URL + Constance.URL_EDUTALK_LOAD_CONTENT, getContentSummaryCallBack);
    }

    /**
     * 获取内容概要回调
     */
    private CustomNetCallBack getContentSummaryCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            List<Rp_ContentSummary> css = mGson.fromJson(data, new TypeToken<ArrayList<Rp_ContentSummary>>() {
            }.getType());
            mAdapter.setmList(css);
            expandGroup();
            if (css == null) {
                ToastUtils.showLong("服务器数据为空");
            }
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取内容概要数据失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            LogUtils.e(ex);
            ToastUtils.showLong("获取内容概要数据失败");
        }
    };


    /**
     * 调用接口提交谈话
     */
    private void submitInterToSer(String stepId) {
        mLoadingDialog.setIsCanBack(false).setMessage("数据加密传输中").show();

        mInter.setDangerEvaluate(mSelectedDangerEvaluate.getDisplay_value());
        mInter.setDangerAction(mSelectedDangerEvaluateSon.getDisplay_value());
        mInter.setEmotionEvaluate(mSelectedEmotionEvaluate.getDisplay_value());
        mInter.setTalkEffect(mSelectedTalkEffect.getDisplay_value());
        mInter.setStepId(stepId);
        mInter.setVoiceContent(mGson.toJson(mAdapter.getCheckedList()));

        File upFile = new File(mInter.getFilePath());
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_EDUTALK_INSERT_EDU, mInter, upFile, insertEduCallBack);
    }

    /**
     * 调用接口提交谈话回调
     */
    private CustomNetCallBack insertEduCallBack = new CustomNetCallBack() {

        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            mLoadingDialog.dismiss();
            ToastUtils.showLong("提交成功");
            EduTalkEvaluateActivity.this.finish();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            mLoadingDialog.dismiss();
            dBManager.insertEdu_interDao(mInter);
            ToastUtils.showLong("上传失败，已加入上传失败列表");
            EduTalkEvaluateActivity.this.finish();
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            LogUtils.e(ex);
            mLoadingDialog.dismiss();
            dBManager.insertEdu_interDao(mInter);
            ToastUtils.showLong("上传失败，已加入上传失败列表");
            EduTalkEvaluateActivity.this.finish();
        }
    };


    @Override
    public void onBackPressed() {
        if (mInter == null) {
            this.finish();
            return;
        }
        //非录音状态
        if (!TextUtils.isEmpty(mInter.getFilePath())) {//有录音文件
            AlertDialog.Builder bd = new AlertDialog.Builder(this);
            AlertDialog ad = bd.create();
            ad.setTitle("提示");
            ad.setMessage("退出将会删除本次录音文件，确认退出？");
            //设置取消选项按钮
            ad.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            //设置确定选项按钮
            ad.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    FileUtils.deleteFile(mInter.getFilePath());
                    EduTalkEvaluateActivity.this.finish();
                }
            });
            ad.show();
        } else {//没有录音文件
            this.finish();
        }
    }


    private void expandGroup() {
        //全部展开
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < mAdapter.getmList().size(); i++) {
                    elv_content_summary.expandGroup(i);
                }
            }
        });
    }
}
